<template>
  <div class="editor">
    <quill-editor
      class="ql-container"
      ref="myQuillEditor"
      v-model:content="content"
      contentType="html"
      @textChange="(e) => $emit('update:modelValue', content)"
      :options="options"
      :style="styles"
    />
  </div>
  <input
    type="file"
    hidden
    accept=".jpg,.png"
    ref="fileBtn"
    style="display: none"
    @change="handleUpload"
    @focus="getTokens"
  />
</template>

<script setup>
  import OSS from 'ali-oss'
  import { getUpdateToken, uploadSysToken } from '@/api/index'
  import { QuillEditor } from '@vueup/vue-quill'
  import '@vueup/vue-quill/dist/vue-quill.snow.css'
  import { reactive, ref, onMounted, computed, watch, defineProps, toRaw } from 'vue'
  import axios from 'axios'
  import { uploadFile } from '@/utils/request'
  import * as qiniu from 'qiniu-js'
  import config from '@/config/index.js'
  import Delta from 'quill-delta'
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
//引入Qill插件
import Quill from "quill";
let fontFamily = ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial', 'Times-New-Roman', 'sans-serif'];
Quill.imports['formats/font'].whitelist = fontFamily;
Quill.register(Quill.imports['formats/font'])
 
let fontSize = ['10px', '12px', '14px', '16px', '20px', '24px','28px', '36px']
Quill.imports['attributors/style/size'].whitelist = fontSize;
Quill.register(Quill.imports['attributors/style/size']);

  const props = defineProps({
    /* 编辑器的内容 */
    modelValue: {
      type: String
    },
    /* 高度 */
    height: {
      type: Number,
      default: null
    },
    /* 最小高度 */
    minHeight: {
      type: Number,
      default: null
    },
    /* 只读 */
    readOnly: {
      type: Boolean,
      default: false
    }
  })

  const myQuillEditor = ref()
  const fileBtn = ref()
//   const Size = Quill.import('attributors/style/size')
// Size.whitelist = [false, '12px', '14px', '16px', '18px', '20px', '32px']
// Quill.register(Size, true)

  onMounted(() => {
    const quill = toRaw(myQuillEditor.value).getQuill()
    if (myQuillEditor.value) {
      quill.getModule('toolbar').addHandler('image', imgHandler)
    }

    toRaw(myQuillEditor.value).setHTML(props.value || '<p></p>')
  })
  const imgHandler = (state) => {
    if (state) {
      getTokens()
      fileBtn.value.click()
    }
  }
  const qiniu_token = ref(null)
  const getTokens = () => {
    // getUpdateToken({}).then((res) => {
    //   qiniu_token.value = res.data.qiniu_token
    // })
  }
  const convertFileToBinary = (file) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      const binaryString = e.target.result

      // 在这里处理二进制字符串
      console.log(binaryString)
      return binaryString
    }
    reader.readAsArrayBuffer(file) // 或者使用readAsBinaryString(file)
  }

  const handleUpload = (e) => {
    const files = Array.prototype.slice.call(e.target.files)

    if (!files) {
      return
    } else {
    }
    const formdata = new FormData()

    formdata.append('file', e.target.files[0])
    formdata.append('key', files[0].name)
    formdata.append('token', qiniu_token.value)

    // uploadFile(formdata).then((res) => {

    //   if (res.key) {
    //     const quill = toRaw(myQuillEditor.value).getQuill()
    //     const length = quill.getSelection().index
    //     // 插入图片，res为服务器返回的图片链接地址
    //     quill.insertEmbed(length, 'image', config.upLoadUrl + res.key)
    //     // 调整光标到最后
    //     quill.setSelection(length + 1)
    //   }
    // })

    uploadSysToken({}).then((res1) => {
      let oss = new OSS({ ...res1.stsToken })
      var fileFormat = files[0].name.split('.')

      let name = Date.now() + '.' + fileFormat[fileFormat.length - 1]

      oss
        .put(res1.filename + name, e.target.files[0], {
          headers: {
            'x-oss-tagging':'del=true' // 1*60*3 //1000 * 60 * 3
          }
        })
        .then((res) => {
          const quill = toRaw(myQuillEditor.value).getQuill()
          const length = quill.getSelection().index
          // 插入图片，res为服务器返回的图片链接地址
          quill.insertEmbed(length, 'image', res.url)
          // 调整光标到最后
          quill.setSelection(length + 1)
        })
        .catch((error) => {
          console.log('发生错误', error)
        })
    })
  }

  const options = ref({
    theme: 'snow',
    bounds: document.body,
    debug: 'warn',
    modules: {
      // 工具栏配置
      toolbar: {
        container: [
          ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
          // ['blockquote', 'code-block'], // 引用  代码块
          [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
          [{ indent: '-1' }, { indent: '+1' }], // 缩进
          [{ size: fontSize  }], // 字体大小
          [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
          [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
          [{ align: [] }], // 对齐方式
          // ['clean'], // 清除文本格式
          ['image'] // ['link', 'image', 'video'], 链接、图片、视频
        ]
      }
    },

    placeholder: '请输入内容',
    readOnly: props.readOnly,
    theme: 'snow'
  })

  const styles = computed(() => {
    let style = {}
    if (props.minHeight) {
      style.minHeight = `${props.minHeight}px`
    }
    if (props.height) {
      style.height = `${props.height}px`
    }
    return style
  })

  const content = ref('')
  watch(
    () => props.modelValue,
    (v) => {
      // if (v !== content.value) {

      // console.log('' + content.value + 'v' + v)
      content.value = [null, '', undefined].includes(v) ? '<p></p>' : v
      // }
    },
    { immediate: true },
    { deep: true }
  )
</script>

<style>
  .editor,
  .ql-toolbar {
    white-space: pre-wrap !important;
    line-height: normal !important;
  }
  .quill-img {
    display: none;
  }
  .ql-snow .ql-tooltip[data-mode='link']::before {
    content: '请输入链接地址:';
  }
  .ql-snow .ql-tooltip.ql-editing a.ql-action::after {
    border-right: 0px;
    content: '保存';
    padding-right: 0px;
  }

  .ql-snow .ql-tooltip[data-mode='video']::before {
    content: '请输入视频地址:';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='10px']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='10px']::before {
  content: '10px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='12px']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='12px']::before {
  content: '12px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='14px']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='14px']::before {
  content: '14px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='16px']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='16px']::before {
  content: '16px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='20px']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='20px']::before {
  content: '20px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='24px']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='24px']::before {
  content: '24px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='28px']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='28px']::before {
  content: '28px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='36px']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='36px']::before {
  content: '36px';
}

  .ql-snow .ql-picker.ql-header .ql-picker-label::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item::before {
    content: '文本';
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='1']::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='1']::before {
    content: '标题1';
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='2']::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='2']::before {
    content: '标题2';
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='3']::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='3']::before {
    content: '标题3';
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='4']::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='4']::before {
    content: '标题4';
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='5']::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='5']::before {
    content: '标题5';
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='6']::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='6']::before {
    content: '标题6';
  }

  .ql-snow .ql-picker.ql-font .ql-picker-label::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item::before {
    content: '标准字体';
  }
  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value='serif']::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value='serif']::before {
    content: '衬线字体';
  }
  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value='monospace']::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value='monospace']::before {
    content: '等宽字体';
  }
  .ql-container {
    height: 400px;
    font-size:'28px';
  }
</style>
